﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using JXC.Core.Models;
using JXC.EFCore;
using JXC.Application.Dtos;
using AutoMapper;
using JXC.EFCore.Helper;
using Microsoft.AspNetCore.Authorization;

namespace JXC.WebAPI.Controllers
{
    /// <summary>
    /// 采购订单控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CaigouOrdersController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly AppDbContext _context;

        public CaigouOrdersController(
            IMapper mapper,
            AppDbContext context)
        {
            _mapper = mapper;
            _context = context;
        }

        /// <summary>
        /// 获取分页采购订单
        /// </summary>
        /// <param name="paramter"></param>
        /// <returns></returns>
        // GET: api/CaigouOrders
        [Route("GetData")]
        [HttpPost]
        public async Task<ActionResult<IEnumerable<CaigouOrder>>> GetCaigouOrder([FromBody] Paramter<CaigouOrder> paramter)
        {
            try
            {
                IQueryable<CaigouOrder> result = _context.CaigouOrder.Include(p => p.UserInfos).Include(p => p.Supplier);



                var res = await PaginationList<CaigouOrder>.CreateAsync(paramter.Page, paramter.Limit, result);

                var res2 = _mapper.Map<IEnumerable<CaigouOrderDto>>(res);
                if (!string.IsNullOrWhiteSpace(paramter.Name))
                {
                    res2 = res2.Where(p => p.SupplierName.Contains(paramter.Name));
                }
                if (!string.IsNullOrWhiteSpace(paramter.BeginTime))
                {
                    DateTime time = Convert.ToDateTime(paramter.BeginTime);
                    res2 = res2.Where(p => p.OrderDate > time);
                }
                if (!string.IsNullOrWhiteSpace(paramter.EndTime))
                {
                    DateTime time = Convert.ToDateTime(paramter.EndTime);
                    res2 = res2.Where(p => p.OrderDate < time);
                }
                return Ok(DataResult(res2, "获取数据成功"));
            }


            catch (Exception)
            {

                throw;
            }

        }


        /// <summary>
        /// 获取审核通过的采购订单
        /// </summary>
        /// <param name="paramter"></param>
        /// <returns></returns>
        [Route("GetAuditedCaiGouOrder")]
        [HttpPost]
        public async Task<ActionResult<IEnumerable<CaigouOrder>>> GetCaigouOrder()
        {
            try
            {
                var res = await _context.CaigouOrder.Include(p => p.UserInfos).Include(p => p.Operator).Where(p => p.ExamineState == 1 && p.Deal == 1).ToListAsync();
                return Ok(DataResult(res, "获取已审核的采购订单成功"));
            }


            catch (Exception)
            {

                throw;
            }

        }


        // GET: api/CaigouOrders/5
        [HttpGet("{id}")]
        public async Task<ActionResult<CaigouOrder>> GetCaigouOrder(Guid id)
        {
            var caigouOrder = await _context.CaigouOrder.FindAsync(id);

            if (caigouOrder == null)
            {
                return NotFound();
            }

            return Ok(DataResult(caigouOrder));
        }

        // PUT: api/CaigouOrders/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [AllowAnonymous]
        [HttpPut("{id}")]
        public async Task<IActionResult> PutCaigouOrder(Guid id, CaigouOrder caigouOrder)
        {
            if (id != caigouOrder.Id)
            {
                return BadRequest();
            }

            _context.Entry(caigouOrder).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CaigouOrderExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/CaigouOrders
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<CaigouOrder>> PostCaigouOrder([FromBody] CaigouOrderDto caigouOrderDto)
        {
            try
            {
                CaigouOrder caigouOrder = _mapper.Map<CaigouOrder>(caigouOrderDto);
                caigouOrder.ExamineState = 1;
                caigouOrder.Deal = 1;
                _context.CaigouOrder.Add(caigouOrder);
                List<CaiGouOrderDetail> caiGouOrderDetails = _mapper.Map<List<CaiGouOrderDetail>>(caigouOrderDto.CaigouOrderDetailDtos);
                foreach (var item in caiGouOrderDetails)
                {
                    item.CaigouOrderId = caigouOrder.Id;
                }
                _context.CaiGouOrderDetails.AddRange(caiGouOrderDetails);
                await _context.SaveChangesAsync();

                return Ok(DataResult(caigouOrder, "录入采购订单成功"));
            }
            catch (Exception e)
            {

                throw;
            }

        }

        // DELETE: api/CaigouOrders/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCaigouOrder(Guid id)
        {
            var caigouOrder = await _context.CaigouOrder.FindAsync(id);
            if (caigouOrder == null)
            {
                return BadRequest(Failed("查询不到这条数据"));
            }

            _context.CaigouOrder.Remove(caigouOrder);
            await _context.SaveChangesAsync();

            return Ok(Success("删除成功"));
        }

        private bool CaigouOrderExists(Guid id)
        {
            return _context.CaigouOrder.Any(e => e.Id == id);
        }
    }
}
